package com.gem.eolane.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gem.eolane.config.AppConfig;
import com.gem.eolane.entity.Admin;
import com.gem.eolane.mapper.AdminMapper;
import com.gem.eolane.utils.PasswordLog;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


@Service
public class AdminService extends ServiceImpl<AdminMapper, Admin> {

    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    AppConfig appConfig;

    //查询员工总数
    public int totalCount(){
        return adminMapper.totalCount();
    }

    //总页数（规定每页显示记录为5）
    public int totalPage(){
        return (adminMapper.totalCount()-1)/5+1;
    }

    //分页查询管理员
    public List<Admin> findAdminList(int currentPage){
        return adminMapper.findAdminList((currentPage-1)*5);
    }

    //逻辑删除
    public void banAdmin(Integer id,Integer delIdent){
        adminMapper.banAdmin(id,delIdent);
    }

    //根据adminNumber查询admin是否存在
    public Admin isAdmin(String adminNumber){
        return adminMapper.isAdmin(adminNumber);
    }

    //插入管理员
    public boolean insertAdmin(String adminNumber,String password,String name){
        //如果账户不存在，则可以添加成功
        if(adminMapper.isAdmin(adminNumber) == null ){
            String p = "createtime："+new Date()+"  password： "+password;
            //存储密码，明文日志
            new PasswordLog().saveDataToFile(p,appConfig.adminPassword);
            //密码加密
            BCryptPasswordEncoder encoder =new BCryptPasswordEncoder();
            String passwordEncode = encoder.encode(password).trim();
            adminMapper.insertAdmin(adminNumber,passwordEncode,name);
            return true;
        }else{
            return false;
        }
    }

    public Admin findQueryUser(String adminNumber){
        return adminMapper.queryAdmin(adminNumber);
    }

}
